<template>
  <div class="yy-page yy-system-template_list">

    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>

    <div class="yy-page-header">
      <div class="yy-page-header_title">
        <el-button :disabled="!search.formData.deptId" color="#009688" @click="onOpenDialog()">创建节目</el-button>
        <span v-if="!search.formData.deptId" style="margin-left: 10px;color:#aaa; font-size: 14px; font-weight: normal;">选择科室后进行操作！</span>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getList"></right-toolbar>
      </div>
    </div>
    <div class="yy-page-data">
      <WidgetTable
          ref="tableDataRef"
          :is-loading="table.isLoading"
          :columns="table.columns"
          :data="table.data"
          :options="table.options"
          :formats="table.formats"
          :paging-data="table.paging"
      >
      </WidgetTable>
    </div>
    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                      closeOnClickModal: true,
                      businessName: '模板',
                    }"
                      @edit-callback="onEditCallback"
    />
    <CreateDialog ref="createDialogRef" @operator-callback="onOperatorCallback"/>
    <CreateByProgramList ref="createByProgramListRef" @add-success="onEditCallback"/>
    <SelectFilePublishSettingModal ref="selectFilePublishSettingRef" @add-success="onEditCallback"/>
  </div>
</template>

<script setup lang="ts">
import {onBeforeMount, defineEmits, reactive, ref} from "vue";
import {formatDate} from "@/utils";
import {ElButton, ElMessage} from "element-plus";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import TemplateApi from "@/api/broadcast/template";
import {BcTemplateModel} from "@/model/BcTemplateModel";
import {useRouter} from "vue-router";
import WidgetFormDialog from "@/components/Widget/WidgetFormDialog.vue";
import ResourceApi from "@/api/broadcast/resource";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {EmployeeModel} from "@/model/EmployeeModel";
import EmployeeApi from "@/api/system/empl";
import CreateDialog from "@/views/broadcast/template/CreateDialog.vue";
import SelectFilePublishSettingModal from "@/views/broadcast/template/SelectFilePublishSettingModal.vue";
import {BcScheduleModel} from "@/model/BcScheduleModel";
import DepartSelector from "@/components/Business/DepartSelector.vue";
import useUserStore from "@/store/modules/user";
import CreateByProgramList from "@/views/broadcast/template/CreateByProgramList.vue";

const router = useRouter()
const userStore = useUserStore()
const $emit = defineEmits({
  //
})
const showSearch = ref(true)
const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new EmployeeModel(),
  searchApiFun: EmployeeApi.listEmployee,
  formData: {
    deptId: userStore.deptId || null,
  },
  formFields: [
    {field: 'deptId', initVal: () => userStore.deptId || null, config: {select: {clearable: true}}, placeholder:'请选择科室', label: '所属科室', type: 'templateField', style:'width: 150px;', component: DepartSelector,
      atChange: ({deptId, depart}) => {
        search.formData.deptId = deptId
        getList()
      }},
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入关键字", label: '关键字', type: 'text', style:'width: 200px;',
      atChange: (searchKey) => {
        search.formData.searchKey = searchKey
        getList()
      }}
  ],
  formButtons: []
})

const loading = ref(false)
const dialog = reactive({
  modelInstance: new BcTemplateModel(),
  saveApiFun: TemplateApi.saveTempalte,
  updateApiFun: TemplateApi.updateTemplate,
  formFields: [
    {field: 'name', label: '节目名称', type: 'text', placeholder: '请输入设备名称', required: [{required: true, message: '名称不能为空', trigger: 'blur'}]},
    {field: 'description', label: '描述', type: 'textarea'},
    {field: 'deptId', initVal: () => search.formData.deptId, label: '科室', type: 'text', hide: true},
  ]
})

const table = reactive({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "fixed": 'left',
      "align": 'center',
      "width": 60
    },
    {
      "field":"name",
      "label":"节目名称",
      "showable":true,
      "fixed": 'left',
    },
    {
      "field":"description",
      "label":"描述",
      "showable":true,
    },
    {
      "field":"state",
      "label":"状态",
      "showable":false,
      "width": 120
    },
    {
      "field":"createBy",
      "label":"创建者",
      "showable":true,
      "width": 120
    },
    {
      "field":"createTime",
      "label":"创建时间",
      "showable":true,
      "width": 160
    },
    {
      "field":"action",
      "label":"操作",
      "width": 190,
      "showable":true,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    pageSize: 50,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  options: {
    highlight: true
  },
  data: [],
  formats: {
    'thumbnail': {
       slot: 'thumbnail'
    },
    'state': {
      textType:'text',
      typeFormat: (val) => BcTemplateModel.getStateItem(val)?.type,
      labelFormat: (val) => BcTemplateModel.getStateItem(val)?.label
    },
    'createTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '预览', elType: 'button', type:"default", value: 'preview', atClick: (data) =>
          {
            window.open('/preview/program/' + data.id)
            // router.push({name: 'PreviewProgram', params: {id: data?.id}})
          }
        },
        {label: '复制', condition: () => false, elType: 'button', type:"default", value: 'copy', atClick: (data) => onCopyTemplate(data)},
        {label: '编辑', elType: 'button', value: 'edit', atClick: (data) => {
            if (data.sourceType === 'file') {
              try{
                const dataConfig = JSON.parse(data.config)
                if (dataConfig.type && dataConfig.type === 'time') {
                  createByProgramListRef.value.onShowDialog(search.formData.deptId, data)
                  return
                }
              }catch (e){}
              selectFilePublishSettingRef.value.onShowDialog(data.deptId, data)
            } else {
              router.push({name: 'EditProgram', params: {id: data?.id}})
            }
          }
        },
        {label: '删除', elType: 'button', type:"danger", value: 'delete', confirm: {title: '您确定要删除吗？', atConfirm: (data) => onDelete(data)}}
      ]
    }
  }
})

const searchFormWidget = ref()
const tableDataRef = ref()
const widgetFormDialogRef = ref()
const createDialogRef = ref()
const createByProgramListRef = ref()
const selectFilePublishSettingRef = ref()

onBeforeMount(() => {
  getList()
  search.formData.deptId = useUserStore().deptId
})

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}

const onCopyTemplate = async (temp) => {
   TemplateApi.copyTemplate(temp.id).then((res) => {
       const index = table.data.findIndex(item => item.id === temp.id)
       if (index >= 0) {
           table.data.splice(index, 0, res)
       }
       ElMessage.success({
           message: '拷贝模板成功',
           showClose: true
       })
   })
}

const handleCreate = async (temp) => {
  if (loading.value) {
    return false
  }
  loading.value = true
  await router.push({
    name: 'TemplateCreate',
    params: {
      tempId: temp.id
    }
  })
}

const getList = (pageIndex: number = 1) => {
  table.isLoading = true
  TemplateApi.listTemplate(search.formData.deptId, search.formData.searchKey, pageIndex, table.paging.pageSize).then((res) => {
    table.data = res.data
    table.paging = Object.assign({}, table.paging, {pageIndex: res.pageIndex, total: res.total})
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (data = null) => {
  createDialogRef.value.onShowDialog(data)
}

const onOperatorCallback = (type: string) => {
  if (type === 'editor') {
    router.push({name: 'EditProgram', params: {id: 'create'}})
  } else if(type==='duration'){
    selectFilePublishSettingRef.value.onShowDialog(search.formData.deptId)
  }else if(type==='time'){
    createByProgramListRef.value.onShowDialog(search.formData.deptId)
  }
}

const onChangeState = (data, status) => {
  const temp = new BcTemplateModel().deserialize(
      Object.assign({}, data, {state: status})
  )
  TemplateApi.updateTemplate(data.id, temp).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    table.data.splice(index, 1, temp)
    ElMessage.success({
      message: '操作成功',
      showClose: true
    })
  })
}

const onDelete = (data) => {
  TemplateApi.deleteTemplate(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    table.data.splice(index, 1)
    ElMessage.success({
      message: '删除成功',
      showClose: true
    })
  })
}

const onEditCallback = (data) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.unshift(data)
  } else {
    table.data.splice(index, 1, data)
  }
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != table.paging.pageIndex) {
    getList(pageIndex);
  }
}

</script>
<style scoped lang="scss">
  .yy-system-template_list {
      height: 100%;
      &-item {
        width: 20%;
        display: inline-flex;
        flex-direction: column;
        margin: 5px 5px;
        cursor: pointer;
        &-content {
          width: 100%;
          height: 0;
          padding-bottom: 50%;
          position: relative;
        }
      }
  }
</style>